<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT">





  <link rel="alternate" href="/atom.xml" title="renhao" type="application/atom+xml">






<meta name="description" content="本文对于promise与generator的原理进行探讨总结，参考教程">
<meta property="og:type" content="article">
<meta property="og:title" content="promise与generator的用法与实现">
<meta property="og:url" content="https://huangrenhao.gitee.io/2019/11/01/js-promise-generator/index.html">
<meta property="og:site_name" content="renhao">
<meta property="og:description" content="本文对于promise与generator的原理进行探讨总结，参考教程">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2020-09-05T07:13:53.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="promise与generator的用法与实现">
<meta name="twitter:description" content="本文对于promise与generator的原理进行探讨总结，参考教程">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://huangrenhao.gitee.io/2019/11/01/js-promise-generator/">





  <title>promise与generator的用法与实现 | renhao</title>
  








<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css"></head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">
  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">renhao</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://huangrenhao.gitee.io/2019/11/01/js-promise-generator/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="renhao">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="renhao">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">promise与generator的用法与实现</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-11-01T08:17:52+08:00">
                2019-11-01
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/js/" itemprop="url" rel="index">
                    <span itemprop="name">js</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2019/11/01/js-promise-generator/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/2019/11/01/js-promise-generator/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1.4k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  6
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>本文对于promise与generator的原理进行探讨总结，<a href="https://yuchengkai.cn/docs/frontend/#promise-%E5%AE%9E%E7%8E%B0" target="_blank" rel="noopener">参考教程</a><a id="more"></a></p>
<h3 id="Promise-A"><a href="#Promise-A" class="headerlink" title="Promise/A"></a>Promise/A</h3><p>典型异步Promise/Deferred模型：Promises/A、Promises/B、Promises/D等（由CommonJS草案抽象而来）</p>
<p>Deferred：延迟对象，触发执行回调函数。</p>
<p>Promises/A行为：</p>
<ul>
<li>Promise操作只会处在3中状态中的一种：未完成态（pending）、完成态（resolve）、失败态（reject）。</li>
<li>Promise的状态只会出现从未完成态向完成态或失败态转化，不能逆反。完成态和失败态不能互相转化。</li>
<li>Promise的状态一旦转化将不能被更改。</li>
</ul>
<p>Promise对象的then()方法：then方法所做的事情就是将回调函数存放起来。</p>
<ul>
<li>接受完成态、错误态的回调方法。在操作完成或出现错误时将会调用对应方法。</li>
<li>可选地支持progress事件回调作为第三个方法</li>
<li>then()方法只接受function对象，其余对象将被忽略</li>
<li>then()方法继续返回promise对象，以实现链式调用 </li>
</ul>
<p>Promise.all 和 Promise.race 传入空数组时，Promise.all 可以将空数组作为 data 传递给 then，而 Promise.race 则不会。</p>
<p>根据<a href="https://promisesaplus.com/" target="_blank" rel="noopener">Promise/A+规范</a>实现Promise：</p>
<pre><code>const PENDING = &#39;pending&#39;;
const RESOLVED = &#39;resolved&#39;;
const REJECTED = &#39;rejected&#39;;

function MyPromise (executor) {
    this.state = PENDING;
    this.value = undefined;
    this.reason = undefined;
    // 解决异步实现，将成功和失败存到各自的数组，一旦reject或resolve就调用其中的回调
    this.onResolvedCallbacks = [];
    this.onRejectedCallbacks = [];

    this.resolve = value =&gt; {
        if (value instanceof MyPromise) {
            return value.then(this.resolve, this.reject);
        }
        // setTimeout 异步执行，保证执行顺序
        setTimeout( () =&gt; {
            if (this.state === PENDING) {
                this.state = RESOLVED;
                this.value = value;
                this.onResolvedCallbacks.forEach(fn =&gt; fn());
            }
        })
    };

    this.reject = reason =&gt; {
        setTimeout( () =&gt; {
            if (this.state === PENDING) {
                this.state = REJECTED;
                this.reason = reason;
                this.onRejectedCallbacks.forEach(fn =&gt; fn());
            }
        })
    };

    try {
        executor(this.resolve, this.reject);
    } catch (err) {
        this.reject(err);
    }
}

MyPromise.prototype.then = function(onFulfilled, onRejected) {
    // onFulfilled,onRejected可选参数
    onFulfilled = typeof onFulfilled === &#39;function&#39; ? onFulfilled : v =&gt; v;
    onRejected = typeof onRejected === &#39;function&#39; ? onRejected : e =&gt; {throw e};

    // 解决链式调用
    let promise2 = new MyPromise ((resolve,reject) =&gt; {
        if (this.state === RESOLVED) {
            // 规范2.2.4
            // 保证 onFulfilled,onRejected异步执行，使用setTimeout包裹
            // 可能会出错，使用try/catch包裹
            setTimeout( () =&gt; {
                try {
                    var x = onFulfilled(this.value);
                    resolvePromise(promise2, x, resolve, reject);
                } catch (reason) {
                    reject(reason);
                }
            })
        }
        if (this.state === REJECTED) {
            setTimeout( () =&gt; {
                try {
                    var x =  onRejected(this.reason);
                    resolvePromise(promise2, x, resolve, reject);
                } catch (reason) {
                    reject(reason);
                }
            })
        }
        if (this.state === PENDING) {
            this.onResolvedCallbacks.push( () =&gt; {
                try {
                    var x = onFulfilled(this.value);
                    resolvePromise(promise2, x, resolve, reject);
                } catch (reason) {
                    reject(reason);
                }
            });
            this.onRejectedCallbacks.push( () =&gt; {
                try {
                    var x =  onRejected(this.reason);
                    resolvePromise(promise2, x, resolve, reject);
                } catch (reason) {
                    reject(reason);
                }
            })
        }
    });

    return promise2;
}

// 规范2.3
// 链式调用中不同promise之间的处理，resolve,reject为promise2的
function resolvePromise(promise2, x, resolve, reject) {
    // 规范2.3.1
    // 循环引用问题，自己等待自己完成，永远完不成
    if (x === promise2) {
        return reject(new TypeError(&#39;chaining cycle detected for promise&#39;));
    }

    // 规范2.3.2
    // 如果 x 是自定义实现的 promise，状态为 pending 需要继续等待
    if (x instanceof MyPromise) {
        if (x.state === PENDING) {
            x.then( value =&gt; {
                resolvePromise( promise2, value, resolve, reject);
            }, reject);
        } else {
            x.then(resolve, reject);
        }
    }

    // 规范2.3.3.3.3
    // 防止多次调用，reject 或者 resolve 其中一个执行过就忽略其他的
    let called;

    // 规范2.3.3
    if (x != null &amp;&amp; (typeof x === &#39;object&#39; || typeof x === &#39;function&#39;)) {
        // x是对象或者函数（包括promise）就需要进行判断
        // 规范2.3.3.2
        // 如果不能取出then就reject
        try {
            // 规范2.3.3.1
            let then = x.then;
            if (typeof then === &#39;function&#39;) {
                // 规范2.3.3.3
                // x是一个promise
                then.call( 
                    x,
                    y =&gt; {
                        if (called) { return; }
                        called = true;
                        // 规范2.3.3.3.1
                        resolvePromise(promise2, y, resolve, reject);
                    }, 
                    err =&gt; {
                        if (called) { return; }
                        called = true;
                        reject(err);
                    });
            } else {
                // 规范2.3.3.4
                // x不是promise
                resolve(x);
            }
        } catch (e) {
            if (called) return;
            called = true;
            reject(e);
        }
    } else {
        // 规范2.3.4
        // x是普通值直接resolve
        resolve(x);
    }
}

// race方法
MyPromise.prototype.race = function (promises) {
    return new MyPromise((resolve, reject) =&gt; {
        for (let i=0; i&lt;promises.length; i++) {
            promises[i].then(resolve, reject);
        }
    })
}

// all方法
MyPromise.prototype.all = function (promises) {
    let arr = [];
    let i = 0;

    function processData (index, data) {
        arr[index] = data;
        i++;
        if(i == promises.length) {
            resolve(arr);
        }
    }

    return new MyPromise((resolve, reject) =&gt; {
        for (let i=0; i&lt;promises.length; i++) {
            promises[i].then(data =&gt; {
                processData(i, data);
            },reject);
        }
    })
}

// test
MyPromise.defer = MyPromise.deferred = function () {
    let dfd = {};
    dfd.promise = new MyPromise((resolve, reject) =&gt; {
        dfd.resolve = resolve;
        dfd.reject = reject;
    });
    return dfd;
}
module.exports = MyPromise;
</code></pre><blockquote>
<p>看不懂就看这里，<a href="https://juejin.im/post/5b2f02cd5188252b937548ab" target="_blank" rel="noopener">参考实现</a></p>
</blockquote>
<h3 id="Generator-实现"><a href="#Generator-实现" class="headerlink" title="Generator 实现"></a>Generator 实现</h3><p>可以将Generator函数理解为一个状态机，内部封装了多个内部状态。Generator函数有两个特征，一个function关键字与函数名之间有一个星号，二是函数体内部使用yield表达式。</p>
<p>调用Generator函数后该函数并不执行，返回一个指向内部状态的指针对象（遍历器对象而不是函数运行结果），必须调用遍历器对象的next方法使指针移向下一个状态。即内部指针从函数头部或上一次停下来的地方开始执行直到遇到下一个yield表达式（或return语句）。</p>
<pre><code>// cb 就是编译过的 test 函数
function myGenerator (cb) {
    return (function() {
        var object = {
            next: 0,
            stop: function() {}
        };

        // b，test()函数执行后的返回对象
        return {
            next: function() {
                var ret = cb(object);
                if (ret === undefined) {
                    return {
                        value: undefined,
                        done: true
                    };
                }
                return {
                    value: ret,
                    done: false
                };
            }
        };
    })();
}

// test 原始函数
function * test() {
    let a = 1+2;
    yield 2;
    yield 3;
}
let b = test();
console.log(b.next()); // &gt; { value: 2, done: false }
console.log(b.next()); // &gt; { value: 3, done: false }
console.log(b.next()); // &gt; { value: undefined, done: true }

// test 经过 babel 编译后的代码
function test() {
    var a;
    return myGenerator(function(_context) {
        while(1) {
            switch((_context.prev = _context.next)) {
                // yield将代码分割成几块，每次执行 next 函数就执行一段代码
                // 并且表明下次需要执行哪块代码
                case 0: 
                    a = 1+2;
                    _context.next = 4;
                    return 2;
                case 4:
                    _context.next = 6;
                    return 3;
                case 6:
                case &#39;end&#39;: 
                    return _context.stop();
            }
        }
    })
}
</code></pre>
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/10/29/js-closure/" rel="next" title="js中的闭包、this、执行上下文">
                <i class="fa fa-chevron-left"></i> js中的闭包、this、执行上下文
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/11/04/js-gabage-collect/" rel="prev" title="垃圾收集">
                垃圾收集 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">renhao</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">94</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">19</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#Promise-A"><span class="nav-number">1.</span> <span class="nav-text">Promise/A</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Generator-实现"><span class="nav-number">2.</span> <span class="nav-text">Generator 实现</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">renhao</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">265.9k</span>
  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: '2P1xqUWiCoNm14MH4yhURlJi-gzGzoHsz',
        appKey: 'uJN0uagHIVgXtBO1OuLV9Ban',
        placeholder: 'Just go go',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  





  

  

  

  
  

  

  

  

</body>
</html>
